
/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2015年4月5日 下午2:28:31
 * @Description: 本内容未经本人允许禁止使用、转发.
 */
 
package com.ls.fw.web.core.servlet.filter;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 
 * @author lisheng
 * @date 2015年4月5日 下午2:28:31
 * @version V1.0 
 */
public class SecrityFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = ((HttpServletResponse) servletResponse);
		// 从 HTTP 头中取得 Referer 值
		 String referer=request.getHeader("Referer"); 
		 // 判断 Referer 是否以 bank.example 开头
		 if((referer!=null) &&(referer.trim().startsWith("bank.example"))){ 
		    chain.doFilter(request, response); 
		 }else{ 
		    request.getRequestDispatcher("error.jsp").forward(request,response); 
		 }
		 HttpServletRequest req = (HttpServletRequest)request; 
		 HttpSession s = req.getSession(); 

		 // 从 session 中得到 csrftoken 属性
		 String sToken = (String)s.getAttribute("csrftoken"); 
		 if(sToken == null){ 

		    // 产生新的 token 放入 session 中
		    sToken = generateToken(); 
		    s.setAttribute("csrftoken",sToken); 
		    chain.doFilter(request, response); 
		 } else{ 

		    // 从 HTTP 头中取得 csrftoken 
		    String xhrToken = req.getHeader("csrftoken"); 

		    // 从请求参数中取得 csrftoken 
		    String pToken = req.getParameter("csrftoken"); 
		    if(sToken != null && xhrToken != null && sToken.equals(xhrToken)){ 
		        chain.doFilter(request, response); 
		    }else if(sToken != null && pToken != null && sToken.equals(pToken)){ 
		        chain.doFilter(request, response); 
		    }else{ 
		        request.getRequestDispatcher("error.jsp").forward(request,response); 
		    } 
		 }
	}

	
	/**
	 * 
	 * @author lisheng
	 * @date 2015年4月5日 下午2:39:51
	 * @version V1.0
	 * @return
	 */
	private String generateToken() {
		return UUID.randomUUID().toString();
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
